//
//  SLSearchView.swift
//  Sina15
//
//  Created by 盼 on 16/4/6.
//  Copyright © 2016年 pan. All rights reserved.
//

import UIKit

class SLSearchView: UIView {

    @IBOutlet weak var textField: UITextField!
    
    @IBOutlet weak var rightConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var cancelBtn: UIButton!

    
    override func awakeFromNib() {
        
        //设置搜索框的frame
        self.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 35)
        
        textField.leftView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
        
        textField.leftView?.frame = CGRect(x: 0, y: 0, width: self.bounds.height, height: self.bounds.height)
        
        //设置图片的显示模式
        textField.leftView?.contentMode = .Center
        
        //设置leftView始终显示，默认是不显示
        textField.leftViewMode = .Always
        
//        //设置文本框的圆角
//        textField.layer.cornerRadius = 8
//        textField.layer.masksToBounds = true
    }

    
    //类方法获取xib
    class func loadSearchView()->SLSearchView {
      
     //从xib获取创建的类
     return  NSBundle.mainBundle().loadNibNamed("SLSearchView", owner: nil, options: nil).last as! SLSearchView
    }
 
    //MARK:点击文本框编辑的时候，显示出cancel按钮
    @IBAction func editDidBegin(sender: AnyObject) {
        
        //获取约束的变化
        self.rightConstraint.constant = self.cancelBtn.frame.width
        
        //在动画闭包中设置执行动画，刷新页面
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.layoutIfNeeded()
        }
    }
    
    
    //MARK:点击取消按钮的触发事件
    
    @IBAction func cancelBtnDidClick(sender: AnyObject) {
        
        //取消键盘的第一响应者
    self.textField.resignFirstResponder()
        
        self.rightConstraint.constant = 0
        UIView.animateWithDuration(0.25) { () -> Void in
            self.layoutIfNeeded()
        }
    }
}


